﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MododorWebAPI.DbContextConfig;
using MododorWebAPI.DTO;
using MododorWebAPI.Models;
using System.Diagnostics.Contracts;
using System.Globalization;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace MododorWebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class Client_CompanyController : ControllerBase
    {
        private readonly MododorDbContext mododorDb;

        public Client_CompanyController(MododorDbContext mododorDb)
        {
            this.mododorDb = mododorDb;
        }

        #region 客户公司表增删改查操作

        /*===========================================客户公司表增删改查操作===========================================================*/
        /// <summary>
        /// 对公司表改插操作
        /// </summary>
        /// <param name="company"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<object>> CompanyModelOperation(Client_Company_CopmanyModelDTO company)
        {
            try
            {
                CompanyModel companyModel = new CompanyModel()
                {
                    id = company.Id,
                    CompanyAdd = company.CompanyAdd,
                    CompanyCity = company.CompanyCity,
                    CompanyDate = DateTime.Now,
                    CompanyNameCh = company.CompanyNameCh,
                    CompanyNameEn = company.CompanyNameEn,
                    CompanyTel = company.CompanyTel,
                    CompanyZip = company.CompanyZip,
                    IdCompany = company.IdCompany,
                    CompanyEnable = true
                };

                var companyEnables = mododorDb.Company.Where(x => x.CompanyEnable == true);
                //包含就是更新数据
                if (await companyEnables.AnyAsync(x => x.id == company.Id))
                {
                    mododorDb.Entry<CompanyModel>(companyModel).State = EntityState.Modified;
                    await mododorDb.SaveChangesAsync();
                    return Ok(new { status = 200, msg = "数据更新成功" });
                }
                //不包含就插入
                await mododorDb.Company.AddAsync(companyModel);
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据插入成功" });

            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message });
            }
        }
        /// <summary>
        /// 数据标记删除
        /// </summary>
        /// <param name="idCompany"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<object>> CompanyModelDelete(long idCompany)
        {
            try
            {
                var companyEnables = mododorDb.Company.Where(x => x.CompanyEnable == true);
                var res = await companyEnables.SingleAsync(x => x.IdCompany == idCompany);
                res.CompanyEnable = false;
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据删除成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message });
            }
        }
        /// <summary>
        /// 公司信息获取
        /// </summary>
        /// <param name="idCompany"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<object>> CompanyModelInfoGet()
        {
            try
            {
                var companyEnables = mododorDb.Company.Where(x => x.CompanyEnable == true);
                return Ok(new { status = 200, msg = "数据查询成功", res = companyEnables });
            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message, res = "null" });
            }
        }

        /*===========================================客户公司表增删改查操作===========================================================*/

        #endregion

        #region 客户员工表增删改查操作

        /*===========================================客户员工表增删改查操作===========================================================*/
        /// <summary>
        /// 对Client客户公司员工表进行插入更新
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<IEnumerable<object>>> ClientModelOperation(Client_Company_ClientModelDTO client)
        {
            try
            {
                var clientEnables = mododorDb.Client.Where(x => x.ClientEN == true);
                var companyEnables = mododorDb.Company.Where(x => x.CompanyEnable == true);
                ClientModel clientModel = new ClientModel()
                {
                    ClientDate = DateTime.Now,
                    ClientEN = true,
                    ClientEmail = client.ClientEmail,
                    ClientJobTitle = client.ClientJobTitle,
                    ClientMobile = client.ClientMobile,
                    ClientNameCh = client.ClientNameCh,
                    idClient = client.idClient,
                    ClientNameEn = client.ClientNameEn,
                    Client_idCompany = await companyEnables.SingleAsync(x => x.id == client.Client_idCompany)
                };
                if (await clientEnables.AnyAsync(x => x.idClient == client.idClient))
                {
                    mododorDb.Entry<ClientModel>(clientModel).State = EntityState.Modified;
                    await mododorDb.SaveChangesAsync();
                    return Ok(new { status = 200, msg = "数据更新成功" });
                }
                await mododorDb.Client.AddAsync(clientModel);
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据插入成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message });
            }
        }
        /// <summary>
        /// 客户公司员工标记删除操作
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<object>> ClientModelDelete(int clientId)
        {
            try
            {
                var clientEnables = mododorDb.Client.Where(x => x.ClientEN == true);
                var clientRes = await clientEnables.SingleAsync(x => x.idClient == clientId);
                clientRes.ClientEN = false;
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据删除成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message });
            }
        }

        /// <summary>
        /// 客户公司员工信息查询
        /// </summary>
        /// <param name="clientId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<object>> ClientModelInfoGet(int idCompany)
        {
            try
            {
                var clientEnables = mododorDb.Client.Where(x => x.ClientEN == true);
                //两表连接获取员工对应的公司信息
                var res = clientEnables.Include(x => x.Client_idCompany)
                                       .Where(x => x.Client_idCompany.id == idCompany)
                                       .Select(x => new
                                       {
                                           IdClient = x.idClient,
                                           CompanyNameCh = x.Client_idCompany.CompanyNameCh,
                                           CompanyNameEn = x.Client_idCompany.CompanyNameEn,
                                           idCompany = x.Client_idCompany.id,
                                           ClientNameCh = x.ClientNameCh,
                                           ClientNameEn = x.ClientNameEn,
                                           ClientEmail = x.ClientEmail,
                                           ClientMobile = x.ClientMobile,
                                           ClientJobTitle = x.ClientJobTitle,
                                           ClientEN = x.ClientEN,
                                           ClientDate = x.ClientDate
                                       });
                //var res = clientEnables.Include(x => x.Client_idCompany)
                //                       .ThenInclude(x => x.Clients.Where(x => x.ClientEN == true));
                return Ok(new { status = 200, msg = "数据查询成功", res = res });
            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message, res = "null" });
            }
        }
        /*===========================================客户员工表增删改查操作===========================================================*/

        #endregion

        #region 客户合同类型表增删改查操作

        /*===========================================客户合同类型表增删改查操作===========================================================*/
        /// <summary>
        /// 对合同类型进行插入更新
        /// </summary>
        /// <param name="contractType"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<IEnumerable<object>>> ContractTypeModelOperation(Client_Company_ContractTypeModelDTO contractType)
        {
            try
            {
                ContractTypeModel updateData = new ContractTypeModel()
                {
                    idContractType = contractType.idContractType,
                    ContractTypeDate = DateTime.Now,
                    ContractTypeDescription = contractType.ContractTypeDescription,
                    ContractTypeEN = true,
                    ContractTypeName = contractType.ContractTypeName
                };
                if (await mododorDb.ContractType.AnyAsync(x => x.idContractType == contractType.idContractType))
                {
                    mododorDb.Entry<ContractTypeModel>(updateData).State = EntityState.Modified;
                    await mododorDb.SaveChangesAsync();
                    return Ok(new { status = 200, msg = "数据更新成功" });
                }

                await mododorDb.ContractType.AddAsync(updateData);
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据插入成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message });
            }
        }

        [HttpGet]
        public async Task<ActionResult<object>> ContractTypeModelDelete(long contractTypeId)
        {
            try
            {
                var contractTypeEnables = mododorDb.ContractType.Where(x => x.ContractTypeEN == true);
                var res = await contractTypeEnables.SingleAsync(x => x.idContractType == contractTypeId);
                res.ContractTypeEN = false;
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据删除成功" });
            }
            catch (Exception ex)
            {

                return Ok(new { status = 200, msg = ex.Message });
            }

        }

        [HttpGet]
        public ActionResult<IEnumerable<object>> ContractTypeModelInfoGet()
        {
            var contractTypeEnables = mododorDb.ContractType.Where(x => x.ContractTypeEN == true);
            return Ok(new { status = 200, msg = "数据查询成功", res = contractTypeEnables });
        }
        /*===========================================客户合同类型表增删改查操作===========================================================*/

        #endregion

        #region 客户合同表增删改查操作

        /*===========================================客户合同表增删改查操作===========================================================*/
        /// <summary>
        /// 对Contract合同表进行改插操作
        /// </summary>
        /// <param name="contractDTO"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<IEnumerable<object>>> ContractModelOperation(Client_Company_ContractModelDTO contractDTO)
        {
            try
            {
                //将数据通过Where的形式拿到内存中，减轻数据库压力
                var client = mododorDb.Client.Include(x => x.Contracts).Where(x => x.ClientEN == true);
                var company = mododorDb.Company.Where(x => x.CompanyEnable == true);
                var contractType = mododorDb.ContractType.Where(x => x.ContractTypeEN == true);
                var contracts = mododorDb.Contract.Include(x => x.ClientModels).Where(x => x.ContractEnable == true);

                ContractModel contract = new ContractModel()
                {
                    Id = contractDTO.Id,
                    ContractDate = DateTime.Now,
                    ContractName = contractDTO.ContractName,
                    ContractActive = contractDTO.ContractActive,
                    ContractContent = contractDTO.ContractContent,
                    ContractEnable = true,
                    ContractEndDate = contractDTO.ContractEndDate,
                    ContractHours = contractDTO.ContractHours,
                    ContractStartDate = contractDTO.ContractStartDate,
                    idContract = contractDTO.idContract,
                    ContractCompanyID = await company.SingleAsync(x => x.id == contractDTO.ContractCompanyID),
                    ContractType = await contractType.SingleAsync(x => x.idContractType == contractDTO.ContractTypeid)
                };

                if (await mododorDb.Contract.AnyAsync(x => x.Id == contractDTO.Id))
                {
                    var contractsById = contracts.Single(x => x.Id == contractDTO.Id);

                    //多对多更新先删除旧数据
                    contractsById.ClientModels.Remove(client.Single(x => x.idClient == contractDTO.ClientBillPersonOld));
                    contractsById.ClientModels.Remove(client.Single(x => x.idClient == contractDTO.ClientSignPersonOld));
                    //插入新数据
                    contractsById.ClientModels.Add(client.Single(x => x.idClient == contractDTO.ClientBillPerson));
                    contractsById.ClientModels.Add(client.Single(x => x.idClient == contractDTO.ClientSignPerson));
                    contractsById.ContractDate = DateTime.Now;
                    contractsById.ContractName = contractDTO.ContractName;
                    contractsById.ContractActive = contractDTO.ContractActive;
                    contractsById.ContractContent = contractDTO.ContractContent;
                    contractsById.ContractEnable = true;
                    contractsById.ContractEndDate = contractDTO.ContractEndDate;
                    contractsById.ContractHours = contractDTO.ContractHours;
                    contractsById.ContractStartDate = contractDTO.ContractStartDate;
                    contractsById.idContract = contractDTO.idContract;
                    contractsById.ContractCompanyID = await company.SingleAsync(x => x.id == contractDTO.ContractCompanyID);
                    contractsById.ContractType = await contractType.SingleAsync(x => x.idContractType == contractDTO.ContractTypeid);

                    await mododorDb.SaveChangesAsync();
                    return Ok(new { status = 200, msg = "数据更新成功" });
                }

                contract.ClientModels = new List<ClientModel>()
                {
                    await client.SingleAsync(x => x.idClient == contractDTO.ClientSignPerson),
                    await client.SingleAsync(x => x.idClient == contractDTO.ClientBillPerson)
                };

                await mododorDb.Contract.AddAsync(contract);
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据插入成功" });
            }
            catch (Exception ex)
            {

                return Ok(new { status = 200, msg = ex.Message });
            }

        }

        [HttpGet]
        public async Task<ActionResult<object>> ContractModelDelete(long contractId)
        {
            try
            {
                var contracts = mododorDb.Contract.Where(x => x.ContractEnable == true);
                var contract = await contracts.SingleAsync(x => x.Id == contractId);
                contract.ContractEnable = false;
                await mododorDb.SaveChangesAsync();
                return Ok(new { status = 200, msg = "数据删除成功" });
            }
            catch (Exception ex)
            {

                return Ok(new { status = 200, msg = ex.Message });
            }

        }

        [HttpGet]
        public ActionResult<IEnumerable<object>> ContractModelInfoGet(long idCompany)
        {
            var enableCompany = mododorDb.Company.Where(x => x.CompanyEnable == true);
            try
            {
                var res = enableCompany.Include(x => x.Contracts)
                                       .ThenInclude(x => x.ContractType)
                                       .Include(x => x.Contracts)
                                       .ThenInclude(x => x.ClientModels)
                                       .Where(x => x.id == idCompany)
                                       .Select(x => new
                                       {
                                           IdCompany = x.IdCompany,
                                           CompanyName = x.CompanyNameCh,
                                           Contracts = x.Contracts.Where(x => x.ContractEnable == true).Select(y => new
                                           {
                                               IdContract = y.Id,
                                               IdContractInput = y.idContract,
                                               ContractContent = y.ContractContent,
                                               ContractName = y.ContractName,
                                               ContractActive = y.ContractActive,
                                               ContractStartDate = y.ContractStartDate,
                                               ContractEndDate = y.ContractEndDate,
                                               ContractType = new
                                               {
                                                   IdContractType = y.ContractType.idContractType,
                                                   ContractTypeName = y.ContractType.ContractTypeName,
                                                   ContractTypeDescription = y.ContractType.ContractTypeDescription
                                               },
                                               ClientModels = y.ClientModels.Where(x => x.ClientEN == true).Select(z => new
                                               {
                                                   IdClient = z.idClient,
                                                   ClientName = z.ClientNameCh,
                                               })
                                           }),

                                       });
                return Ok(new { status = 200, msg = "数据查询成功", res = res });
            }
            catch (Exception ex)
            {
                return Ok(new { status = 200, msg = ex.Message, res = "null" });
            }
        }
        /*===========================================客户合同表增删改查操作===========================================================*/
        /*===========================================客户合同表编号查找操作===========================================================*/
        #region 客户合同表编号生成
        [HttpGet]
        public async Task<ActionResult<object>> ContractAutoIdGet()
        {
            int count = await mododorDb.Contract.CountAsync();
            return Ok(new { status = 200, msg = "数量获取成功", res = $"{DateTime.Now.ToString("yyyyMM")}{count + 1}" });
        }
        #endregion
        /*===========================================客户合同表编号查找操作===========================================================*/


        #endregion

        #region 客户根据公司查询所有数据操作

        /*===========================================客户根据公司查询所有数据操作===========================================================*/
        /// <summary>
        /// 获取对应的数据
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult<IEnumerable<object>> SeletcData(int IdCompany)
        {
            var enableCompany = mododorDb.Company.Where(x => x.CompanyEnable == true);
            try
            {
                var res = enableCompany.Include(x => x.Clients.Where(y => y.ClientEN == true))
                                       .Include(x => x.Contracts.Where(y => y.ContractEnable == true))
                                       .ThenInclude(x => x.ClientModels.Where(y => y.ClientEN == true))
                                       .Single(x => x.id == IdCompany);
                return Ok(new
                {
                    status = 200,
                    msg = "数据查询成功",
                    res = res
                });
            }
            catch (Exception ex)
            {
                return Ok(new
                {
                    status = 200,
                    msg = ex.Message,
                    res = "null"
                });
            }
        }
        /*===========================================客户根据公司查询所有数据操作===========================================================*/
        #endregion
    }
}
